import 'package:dio/dio.dart' hide Response;
import 'package:dio/dio.dart' as dio show Response;
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:sinosheets/network/interceptor/network_status_interceptor.dart';
import 'package:sinosheets/network/interceptor/token_interceptor.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

class InterceptorManager {
  /// 单例
  static final InterceptorManager _instance = InterceptorManager._internal();
  factory InterceptorManager() => _instance;

  /// 网络状态拦截器
  late final NetworkStatusInterceptor networkStatusInterceptor;

  /// Token拦截器
  late final TokenInterceptor tokenInterceptor;

  /// 数据转换拦截器
  late final TransformInterceptor transformInterceptor;

  InterceptorManager._internal() {
    // 初始化网络状态管理器
    Get.put(NetworkManager());

    networkStatusInterceptor = NetworkStatusInterceptor();
    tokenInterceptor = TokenInterceptor();
    transformInterceptor = TransformInterceptor();
  }

  /// 添加拦截器到Dio实例
  void addTo(Dio dio) {
    // 1. 网络状态拦截器（最先检查网络状态）
    dio.interceptors.add(networkStatusInterceptor);

    // 2. Token拦截器（其次添加认证信息）
    dio.interceptors.add(tokenInterceptor);

    // 3. 数据转换拦截器（转换请求/响应数据格式）
    dio.interceptors.add(transformInterceptor);

    // 5. 日志拦截器（最后记录完整的请求/响应信息）
    if (kDebugMode) {
      dio.interceptors.add(PrettyDioLogger(
        request: true,
        requestHeader: false,
        requestBody: true,
        responseHeader: false,
        responseBody: true,
        error: true,
        compact: true,
        maxWidth: 90,
      ));
    }
  }

  /// 释放资源
  void dispose() {
    Get.delete<NetworkManager>();
  }
}

/// 数据转换拦截器
class TransformInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 统一处理请求数据
    if (options.data != null && options.data is Map) {
      // 移除空值
      (options.data as Map).removeWhere((key, value) => value == null);
    }
    handler.next(options);
  }

  @override
  void onResponse(dio.Response response, ResponseInterceptorHandler handler) {
    // 统一处理响应数据
    if (response.data != null && response.data is Map) {
      // 处理日期格式等
      _transformResponseData(response.data);
    }
    handler.next(response);
  }

  /// 转换响应数据
  void _transformResponseData(Map<String, dynamic> data) {
    // 示例：转换日期字符串为DateTime
    data.forEach((key, value) {
      if (value is String && key.toLowerCase().contains('time')) {
        try {
          data[key] = DateTime.parse(value);
        } catch (_) {}
      }
    });
  }
}
